// 虚拟DOM，用于上传图片文件
let r_in = document.createElement('input');
r_in.type = 'file';
r_in.setAttribute('accept', 'image/*');

// 设置点击头像的事件


let input_img = document.querySelector(".photo_inner_box");
let portrait = input_img.querySelector('.photo1');
let values = localStorage.getItem("jwt");
let name_edit = document.querySelector(".name_edit span");
let sex = document.querySelector(".gender");
let brief = document.querySelector(".brief");
input_img.addEventListener('click', (e) => {
    r_in.click();
});
// 定义用户再次选择新图片的事件
r_in.addEventListener('change', function (e) {
    let files = r_in.files;
    if (files.length > 0) {
        // 获取文件句柄
        let file = files[0];
        // 读取文件内容
        let reader = new FileReader();
        reader.onload = function (e) {
            let base64String = e.target.result;
            // console.log('111111111111', base64String);

            portrait.src = base64String;
            let data = {
                img: base64String
            };
            fetch('/user_message/updateImg', {
                method: 'POST',
                headers: {
                    'authorization': values,
                    'content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络请求错误: ' + response.status + ' ' + response.statusText);
                }
                return response.json();
            }).catch(error => {
                console.error(error);
            })

        };
        // 读取文件为 Base64编码
        reader.readAsDataURL(file);
    }
});



(function () {
    fetch('/user_message/userBrief', {
        method: 'GET',
        headers: {
            'authorization': values
        }
    }).then(response => {
        if (!response.ok) {
            throw new Error('网络请求错误: ' + response.status + ' ' + response.statusText);
        }
        return response.json();
    }).then(data => {
        data[0]['user_icon'] = data[0]['user_icon']['data']
            .map(code => String.fromCharCode(code)).join('');

        sex.textContent = data[0]['sex']  // 性别
        name_edit.textContent = data[0]['username'] // 用户名
        portrait.src = data[0]['user_icon'] // 头像
        data[0]['profile']?brief.textContent = data[0]['profile']:''; // 简介 有写的话就把内容附加没写就算了 
    })
})();



